/**
 * Created by jackliu on 16/11/23.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var ItbBaseModel = require('./ItbBaseModel');
var TgUserPageModel = require('./TgUserPageModel');


// Schema 结构
var TgOutlineModel = function(obj){
    ItbBaseModel.call(this,obj);

    // 以下为表定义数据，需要的字段就填入
  //`tg_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '提纲/提纲模版id',
  //`base_tg_id` bigint(20) DEFAULT NULL COMMENT '来源(提纲模版id)',
  //`master` int(1) NOT NULL DEFAULT '0' COMMENT '0:提纲 1:提纲模版',
  //`fast` int(1) NOT NULL DEFAULT '0' COMMENT '0:普通 1:快速创建用 题纲中有效',
  //`tg_name` varchar(100) NOT NULL DEFAULT '' COMMENT '提纲名',
  //`type_id` bigint(20) NOT NULL DEFAULT '0' COMMENT '提纲类型',
  //`user_id` bigint(20) NOT NULL COMMENT '用户id',
  //`publish` int(1) NOT NULL DEFAULT '0' COMMENT '0制作中; 1已完成',
  //`data` mediumtext COMMENT '提纲json数据',
  //`order` int(3) NOT NULL DEFAULT '999' COMMENT '显示顺序',
  //`ver` int(10) NOT NULL DEFAULT '0' COMMENT '版本号',
  //`create_time` datetime NOT NULL,
  //`update_time` datetime NOT NULL,
  //`update_by` varchar(50) NOT NULL DEFAULT '',
  //`del_flg` int(1) NOT NULL DEFAULT '0',

};
TgOutlineModel.prototype = new ItbBaseModel();

// 取得表名
TgOutlineModel.prototype.getTableName = function(){
    return 'tg_outline';
}
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
TgOutlineModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'tg_id='+this.tg_id;
}

//------------------------------------------------------------------
/* 根据type获取fast提纲
 * 参数:user_id
 * 参数:callback:回调
 * */
TgOutlineModel.prototype.getFastOutlineByType = function(typeL,typeM,typeS,callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = ' SELECT x.* FROM ( '+
            ' SELECT o.*, t.top_parent FROM TG_OUTLINE o, TG_TYPE t '+
            ' WHERE t.del_flg=0 AND t.type_id=o.type_id AND o.del_flg=0 AND o.fast=1 ';
        if(Number(typeL||'0')>0) {
            sql += ' AND t.top_parent='+typeL;
        }
        if(Number(typeM||'0')>0) {
            sql += ' AND t.parent='+typeM;
        }
        if(Number(typeS||'0')>0) {
            sql += ' AND t.type_id='+typeS;
        }
        sql += ' ORDER BY o.update_time) x LIMIT 1 ';

        //var sqlValue = [THIS.type_id];
        //sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            //console.log();

            callback(error, result);
        });
    });
}
//---------------------------------end-------------------------------


// 导出
module.exports = TgOutlineModel;